<template>
  <view>
    <view class="w100 rowsb rowsm h-120 pl-40 pr-40">
      <view class="w100 rowsb rowsm h100 trt" style="border-bottom: 2rpx solid rgba(112, 112, 112, .1);">
        <view class="fs-28 col333 fw-b">劳动项目：</view>
        <input type="text" placeholder="请输入您的劳动项目" placeholder-class="fs-28 col888" v-model="name">
      </view>
    </view>
     <view class="w100 rowsb rowsm h-120 pl-40 pr-40">
      <view class="w100 rowsb rowsm h100 trt" style="border-bottom: 2rpx solid rgba(112, 112, 112, .1);" @tap="show = true">
        <view class="fs-28 col333 fw-b">劳动开始时间：</view>
        <view v-if="startTime">{{startTime}}</view>
        <view v-else class="fs-28 col888">请选择劳动开始时间</view>
      </view>
    </view>
    <u-datetime-picker
      :show="show"
      mode="datetime"
       v-model="value1"
      @confirm="confirmStartTime"
      @cancel="show = false"
    ></u-datetime-picker>
     <view class="w100 rowsb rowsm h-120 pl-40 pr-40">
      <view class="w100 rowsb rowsm h100 trt" style="border-bottom: 2rpx solid rgba(112, 112, 112, .1);" @tap="endTimeShow = true">
        <view class="fs-28 col333 fw-b">劳动结束时间：</view>
        <view v-if="endTime">{{endTime}}</view>
        <view v-else class="fs-28 col888">请选择劳动结束时间</view>
      </view>
    </view>
    <u-datetime-picker
      :show="endTimeShow"
      mode="datetime"
       v-model="value1"
      @confirm="confirmEndTime"
      @cancel="endTimeShow = false"
    ></u-datetime-picker>
    <view class="w100 rowsb rowsm h-120 pl-40 pr-40">
      <view class="w100 rowsb rowsm h100 trt" style="border-bottom: 2rpx solid rgba(112, 112, 112, .1);">
        <view class="fs-28 col333 fw-b">劳动地点：</view>
        <input type="text" placeholder="请输入您的劳动地点" placeholder-class="fs-28 col888" v-model="address">
      </view>
    </view>
    
    <view class="w100 pt-40">
      <view class="pl-40 pr-40 w100 fs-28 col333 fw-b mb-20">劳动过程：</view>
      <view class="w100 pl-24 pr-24">
        <view class="w100 br-10 p-all-40 mb-20" style="background-color: #F7F6FA;">
          <textarea value="" class="w100" auto-height placeholder="请输入您的劳动说明" placeholder-class="fs-28 col888" v-model="info" />
        </view>
        <view class="w100 h-140 br-10 rows rowsm pl-40" style="background-color: #F7F6FA;" @click="choseFile" >
          <image src="/static/icon_cs.png" class="w-60 h-60 mr-20" mode=""></image>
          <!-- <view class="fs-28 col888">（可上传word、pdf、excel、图片、视频）</view> -->
		  <view class="fs-28 col888">（可上传word、pdf、excel、图片）</view>
        </view>
        <!-- <view class="fs-28 mark" >附件不能大于100M</view> -->
		<view class="fs-28 mark" >附件不能大于6M（每张图片大小建议不超过1M）</view>
        
        <view class="w100 h-140 br-10 rowsb rowsm pl-40" style="background-color: #F7F6FA;" v-for="(item,index) in fileList" :key="index">
          <view class="rows rowsm w-500">
            <image src="/static/file.png" class="w-60 h-60 mr-20" mode=""></image>
            <view class="fs-28 col888 w100 one_overflow">{{item.fileName}}</view>
          </view>
          <view class="w-120 h-60 br-30 rowsc rowsm colfff fs-24" style="background: linear-gradient(to bottom,#4897FF,#4878FF);" @click="handelDelete(item)">删除</view>
        </view>
      </view>
    </view>
    
    <view class="w100 h-200"></view>
    
    
    <view class="w100 rowsc rowsm fixed" style="bottom: 100rpx;">
      <view class="w-702 h-84 br-42 rowsc rowsm colfff" style="background: linear-gradient(to bottom,#4897FF,#4878FF);" @click="submit()">提交</view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        value1: Number(new Date()),
        workStartFlag:'',
        workEndFlag:'',
        show: false,
        endTimeShow:false,
        name:'',
        startTime:'',
        endTime:'',
        address:'',
        info:'',
        type:'',
        file:'',
        fileType:'',
        fileName:'',
        id:'',
        fileList:[],
       
      };
    },
    onLoad(e) {
      console.log('ee',e)
      if(e.id){
        this.id = e.id
        this.getInfo()
      }
      this.type = e.type
      uni.setNavigationBarTitle({
        title:e.title
      })
    },
    methods:{
       hideKeyboard() {
      uni.hideKeyboard();
    },
      // 劳动开始时间
     confirmStartTime(e){
      this.workStartFlag = e.value;
      if(this.workEndFlag && e.value >= this.workEndFlag){
         this.$tools.showtt('开始日期不能大于结束日期')
          this.startTime = "";
          this.endTime = "";
          this.workEndFlag = ''
          this.workStartFlag = "";
          this.show = false;
      } else {
        this.startTime= this.formatDateTime(e.value);
        this.show = false;
      }
     },
    //  劳动结束时间
    confirmEndTime(e){
      this.workEndFlag = e.value;

      // 每次活动不少于0.5小时
      if(this.workStartFlag ){
        if ( this.workStartFlag > e.value) {
          this.$tools.showtt('开始日期不能大于结束日期')
          this.startTime = "";
          this.endTime = "";
          this.endTimeShow = false;
          this.workEndFlag = ''
          this.workStartFlag = "";
        }else if(this.type =='1'){
          const minDuration = 30 * 60 * 1000;
          const duration = e.value -  this.workStartFlag ;
          if (duration < minDuration) {
            this.$tools.showtt('活动时间不能少于30分钟');
            this.startTime = "";
            this.endTime = ''
            this.endTimeShow = false;
            this.workEndFlag = ''
            this.workStartFlag = "";
            return;
          }else{
            this.endTime= this.formatDateTime(e.value);
            this.endTimeShow = false;
          }
        }else if(this.type == '2'){
          const minDuration = 60 * 60 * 1000;
          const duration =  e.value -  this.workStartFlag ;
          if (duration < minDuration) {
            this.$tools.showtt('活动时间不能少于1小时');
            this.startTime = "";
            this.endTime = ''
            this.endTimeShow = false;
            this.workEndFlag = ''
            this.workStartFlag = "";
            return;
          }else{
            this.endTime= this.formatDateTime(e.value);
            this.endTimeShow = false;
          }
        }else if(this.type == '3' ||this.type == '9' ||this.type == '10'){
          const minDuration = 120 * 60 * 1000;
          const duration =  e.value -  this.workStartFlag ;
          if (duration < minDuration) {
            this.$tools.showtt('活动时间不能少于2小时');
            this.startTime = "";
            this.endTime = ''
            this.endTimeShow = false;
            this.workEndFlag = ''
            this.workStartFlag = "";
            return;
          }else{
            this.endTime= this.formatDateTime(e.value);
            this.endTimeShow = false;
          }
        }else{
          this.endTime= this.formatDateTime(e.value);
          this.endTimeShow = false;
        }
      }else {
        this.endTime= this.formatDateTime(e.value);
        this.endTimeShow = false;
      }
     
     },
    //  转换时间格式
      formatDateTime(timeStamp) {
        const date = new Date(timeStamp);
        let year = date.getFullYear();
        let month = this.padStart(date.getMonth() + 1);
        let day = this.padStart(date.getDate());
        let hours = this.padStart(date.getHours());
        let minutes = this.padStart(date.getMinutes());
        let seconds = this.padStart(date.getSeconds());
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      },
      padStart(value) {
        return value.toString().padStart(2, '0');
      },
      getInfo(){
        this.$tools.axiosFromToken('POST','prold/getById',{id:this.id},'加载中').then(res => {
          if(res.code != 200) return this.$tools.showtt(res.msg)
          let {data} = res
          
          
          this.address = data.position
          this.endTime = data.stopTime
          this.startTime = data.startTime
          this.name = data.name
          this.info = data.content
          // this.file = data.file
          // this.fileType = data.fileType
          // this.fileName = data.fileName
          this.fileList = data.proFileList
        })
      },
      handelDelete(item){
        this.fileList.splice(item,1)
      },




	  choseFile() {
	    if (this.fileList.length === 6) return this.$tools.showtt('最多上传6个文件');

	    let currentTotalSize = this.fileList.reduce((acc, item) => {
	      return acc + item.size;
	    }, 0);

	    uni.showActionSheet({
	      itemList: ['图片', '文件'],
	      success: (index, e) => {
	        if (index.tapIndex === 0) {
	          uni.chooseImage({
	            count: 6 - this.fileList.length,
	            success: (res1) => {
	              res1.tempFilePaths.forEach(item => {
	                // 检查单个文件大小，6MB = 6 * 1024 * 1024
	                if (res1.tempFiles[0].size > 6 * 1024 * 1024) {
	                  this.$tools.showtt('图片大小不能超过6MB');
	                  return;
	                }
	                // 检查总文件大小
	                currentTotalSize += res1.tempFiles[0].size;
	                if (currentTotalSize > 6 * 1024 * 1024) {
	                  this.$tools.showtt('附件总大小不能超过6MB');
	                  currentTotalSize -= res1.tempFiles[0].size; // 回退当前大小
	                  return;
	                }
	                uni.uploadFile({
	                  url: this.$tools.httpOne + 'utils/ossUpload',
	                  filePath: item,
	                  name: 'file',
	                  header: {
	                    "Content-Type": "multipart/form-data"
	                  },
	                  success: (res) => {
	                    if (JSON.parse(res.data).code === 200) {
	                      this.fileList.push({
	                        fileName: JSON.parse(res.data).newFileName,
	                        fileType: 'image',
	                        file: JSON.parse(res.data).url,
	                        size: res1.tempFiles[0].size // 保存文件大小
	                      });
	                    } else {
	                      this.$tools.showtt('上传失败');
	                    }
	                  }
	                });
	              });
	            }
	          });
	        }
	        if (index.tapIndex === 1) {
	          wx.chooseMessageFile({
	            count: 1,
	            type: 'file',
	            success: (res1) => {
	              if (res1.tempFiles[0].type === "video") {
	                this.$tools.showtt('无法上传视频文件');
	                return;
	              }
	              // 检查单个文件大小，6MB = 6 * 1024 * 1024
	              if (res1.tempFiles[0].size > 6 * 1024 * 1024) {
	                this.$tools.showtt('文件大小不能超过6MB');
	                return;
	              }
	              // 检查总文件大小
	              currentTotalSize += res1.tempFiles[0].size;
	              if (currentTotalSize > 6 * 1024 * 1024) {
	                this.$tools.showtt('附件总大小不能超过6MB');
	                currentTotalSize -= res1.tempFiles[0].size; // 回退当前大小
	                return;
	              }
	              uni.uploadFile({
	                url: this.$tools.httpOne + 'utils/ossUpload',
	                filePath: res1.tempFiles[0].path,
	                name: 'file',
	                success: (res) => {
	                  if (JSON.parse(res.data).code === 200) {
	                    this.fileList.push({
	                      fileName: JSON.parse(res.data).originalFilename,
	                      fileType: res1.tempFiles[0].type,
	                      file: JSON.parse(res.data).url,
	                      size: res1.tempFiles[0].size // 保存文件大小
	                    });
	                  } else {
	                    this.$tools.showtt('上传失败');
	                  }
	                }
	              });
	            }
	          });
	        }
	      }
	    });
	  },
      submit(){
        console.log('fileList',this.fileList)
        if(!this.name) return this.$tools.showtt('请输入项目')
        if(!this.startTime) return this.$tools.showtt('请选择时间')
        if(!this.endTime) return this.$tools.showtt('请选择时间')
        if(!this.address) return this.$tools.showtt('请输入地点')
        if(!this.info) return this.$tools.showtt('请输入过程')
        if(this.fileList.length ==0) return this.$tools.showtt('请上传文件')
        let data = {
          type:this.type,
          name:this.name,
          startTime:this.startTime,
          stopTime:this.endTime,
          position:this.address,
          content:this.info,
          file:this.file,
          fileType:this.fileType,
          fileName:this.fileName,
          id:this.id,
          proFileList:this.fileList
        }
        if(!this.id){
          this.$tools.axiosFromToken('POST','prold/add',{...data},'加载中').then(res => {
            this.$tools.showtt(res.msg)
            if(res.code != 200) return
            setTimeout(() => {
              this.$tools.goBack(1)
            },1000)
          })
        }else {
          this.$tools.axiosFromToken('POST','prold/update',{...data},'加载中').then(res => {
            this.$tools.showtt(res.msg)
            if(res.code != 200) return
            setTimeout(() => {
              this.$tools.goBack(2)
            },1000)
          })
        }
      }
    }
  }
</script>

<style lang="scss">
page {
  background-color: #fff;
}
.mark{
  text-align: right;
  color: #f92929;
}
</style>
